package com.lora.web;

import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@Slf4j
@Service
public class LowerHairService {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    public  void lowerHair(String eid,String data){
        log.info("执行查询设备号为{},查询命令{}", eid, data);
        Map<String, Object> map = jdbcTemplate.queryForMap("SELECT value FROM `sys_config` where name='username'");
        Map<String, Object> map1 = jdbcTemplate.queryForMap("SELECT value FROM `sys_config` where name='password'");
        Map<String, Object> url = jdbcTemplate.queryForMap("SELECT value FROM `sys_config` where name='url'");
        String username=(String) map.get("value");
        String password=(String) map1.get("value");
        String urlStr = (String) url.get("value");
        JSONObject object=new JSONObject();
        JSONObject object1=new JSONObject();
        object.put("password",password);
        object.put("username",username);
        try {
            String token = redisTemplate.opsForValue().get("loraToken");
            if(StringUtils.isBlank(token)) {
                String tokenObj = doPost(urlStr+"/api/v1/user/login",object.toJSONString(),"");
                token = JSONObject.parseObject(tokenObj).getString("jwt");
                redisTemplate.opsForValue().set("loraToken", token);
                redisTemplate.expire("loraToken", 1, TimeUnit.HOURS);
            }
            object1.put("confirmed",false);
            object1.put("data",data);
            object1.put("devEUI",eid);
            object1.put("fPort",220);
            object1.put("reference","string");
            String as = doPost(urlStr+"/api/v1/nodes/"+eid+"/queue",object1.toJSONString(),token);
            // log.info("执行查询设备号为{},查询命令{},查询结果为:{}", eid, data, as);
        } catch (IOException e) {
            log.error("执行查询命令出错:{}", e);
        }

    }

    public static String doPost(String urlStr, String content, String token) throws IOException {
        HttpURLConnection conn = null;
        OutputStream out = null;
        String rsp = null;
        try {
            try {
                String ctype = "application/json";
                URL url = new URL(urlStr);
                conn = (HttpURLConnection) url.openConnection();
                conn.setRequestMethod("POST");
                conn.setDoInput(true);
                conn.setDoOutput(true);
                conn.setRequestProperty("Accept", "text/xml,text/javascript,text/html,application/json");
                conn.setRequestProperty("Content-Type", ctype);
                if(StringUtils.isNotBlank(token)) {
                    conn.setRequestProperty("Authorization", "bearer " + token);
                }
                conn.setConnectTimeout(10000);
                conn.setReadTimeout(10000);
                out = conn.getOutputStream();
                out.write(content.getBytes("utf-8"));
                BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream(), "utf-8"));
                StringWriter writer = new StringWriter();
                char[] chars = new char[256];
                int count = 0;
                while ((count = reader.read(chars)) > 0) {
                    writer.write(chars, 0, count);
                }
                rsp = writer.toString();
            } catch (IOException e) {
                e.printStackTrace();
            }
        } finally {
            if (out != null) {
                out.close();
            }
            if (conn != null) {
                conn.disconnect();

            }
        }
        return rsp;
    }

}
